home *** CD-ROM | disk | FTP | other *** search
- Path: fire.wildfire.com!newsadm
- From: Stonewall Ballard <stoney@wildfire.com>
- Newsgroups: comp.lang.c++
- Subject: Re: beginner question - typecasting
- Date: Fri, 05 Jan 1996 18:04:44 -0500
- Organization: Wildfire Communications
- Message-ID: <30EDAE8C.582@wildfire.com>
- References: <4cei1r$s02@sun.cis.smu.edu> <30EBCED7.774@sto.fdata.se>
- NNTP-Posting-Host: zaphod.wildfire.com
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0b4 (WinNT; I)
- CC: stoney@usa1.com
-
- Niklas Mellin wrote:
- >
- > Damon Bowman wrote:
- > >
- > > When you are typecasting, is there any difference between:
- > >
- > > a = int(x)
- > > and
- > > a = (int) x
- >
- > [...]
- >
- > Yes the first is not type casting, but a "type conversion".
- >
- > When x is a variables of built in types there is no
- > difference. But if x is a varible of some class for instance
- > the first form generates a call to that class' operator int(),
- > generating a compile time error message if there is no such
- > member function.
- >
- > The 2nd form is an inheritance from plain C, and doesn't work
- > when x is of class type. It is also
- > not "safe", meaning that the compiler will not generate error
- > messages in certain situations, and you will get buggy code
- > or run time errors instead.
-
- This is not true. The only difference between these forms is the syntax.
- See section 3.2.5 in Stroustrup's "The C++ Programming Language" 2nd
- edition.
-
- Try compiling this:
-
- ------
-
- class y;
-
- class x
- {
- public:
- x(const y&);
- };
-
- class y
- {
- };
-
- int main()
- {
- y aY;
- x anX = (x)aY; // cast notation using class name
- }
-
- x::x(const y&)
- {
- }
-
- ------
-
- I tried this in GCC and Unixware 2.0's C++ compiler. Both made a call on
- the conversion function.
-
- >
- > In general u should choose the conversion form if possible,
- > but sometimes a type cast can be handy. One case is if you
- > are using a 3rd part class library that is not well written
- > (read MFC) and they forgot to declare function parameters as
- > const and you have a const object you would like to pass to
- > that function. Then you can type cast your object or variable
- > to non const.
- >
- > ---
- > Niklas Mellin---------------------------------------------------------------
- Stonewall Ballard
- stoney@wildfire.com (work) Wildfire Communications, Inc.
- stoney@beeblebrox.com (home) http://www.tiac.net/users/stoney/
-